package com.education.teach.utils;

import android.content.Context;
import android.util.Log;

import com.education.teach.mvp.model.bean.LoginBean;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.math.BigDecimal;
import java.text.DecimalFormat;

import dn.easy.common.commonutils.JsonUtils;
import dn.easy.common.commonutils.SPUtils;

/**
 * Class name
 * Created by  2018/7/17 0017 19:55.
 * Author by yangjing
 */
public class DnCommonUtils {

    /**
     * 提供精确的加法运算。
     *
     * @return 两个参数的和
     */
    public static double add(double v1, double v2) {
        BigDecimal b1 = new BigDecimal(Double.toString(v1));
        BigDecimal b2 = new BigDecimal(Double.toString(v2));
        double sum = b1.add(b2).doubleValue();
        return sum;
    }

    /**
     * 保存小数点后两位
     */
    public static String subFlotTow(double sum) {
        DecimalFormat df = new DecimalFormat("#.##");
        String st = df.format(sum);
        return st;
    }

    //文件转 byte数组
    public static byte[] File2byte(String filePath) {
        byte[] buffer = null;
        try {
            File file = new File(filePath);
            FileInputStream fis = new FileInputStream(file);
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            byte[] b = new byte[1024];
            int n;
            while ((n = fis.read(b)) != -1) {
                bos.write(b, 0, n);
            }
            fis.close();
            bos.close();
            buffer = bos.toByteArray();
        } catch (FileNotFoundException e) {
            Log.i("dn", e.getMessage());
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return buffer;
    }

    public static boolean createDir(String destDirName) {
        File dir = new File(destDirName);
        if (dir.exists()) {
            return false;
        }
        if (!destDirName.endsWith(File.separator)) {
            destDirName = destDirName + File.separator;
        }
        //创建目录
        if (dir.mkdirs()) {
            return true;
        } else {
            return false;
        }
    }

    public static void setUserModel(Context Context, LoginBean loginBean) {
        SPUtils.setSharedStringData(Context, "USER_MODEL", JsonUtils.toJson(loginBean));
    }

    public static LoginBean getUserModel(Context Context) {
        String json = SPUtils.getSharedStringDatas(Context, "USER_MODEL");
        return (LoginBean) JsonUtils.fromJson(json, LoginBean.class);
    }
}
